'''
中间件
'''
from django.utils.deprecation import MiddlewareMixin
from chart_web import models
from django.conf import settings
from django.shortcuts import render, redirect, HttpResponse
import datetime


class ChartWeb():
    def __init__(self):
        self.user = None
        self.price_policy = None


class auth_middleware(MiddlewareMixin):
    def process_request(self, request):
        # 获取当前用户，进行封装
        user_id = request.session.get('user_id')
        user_obj = models.UserInfo.objects.filter(id=user_id).first()
        request.chart_web = ChartWeb()
        request.chart_web.user = user_obj

        # 查看是否在白名单，是放行
        if request.path_info in settings.WHITE_LIST:
            return
        # 未登录，且不在白名单，重定向到home
        if not request.chart_web.user:
            return redirect('register_login')

        # 价格策略的封装
        # 0.查询免费的交易记录中的价格策略，
        free_price_policy = models.Transaction.objects.filter(userinfo=request.chart_web.user).order_by(
            'id').first().price_policy
        # 1.按照id查询当前用户id最大的一个交易记录中的价格策略，
        pay_price_policy = models.Transaction.objects.filter(userinfo=request.chart_web.user).order_by(
            '-id').first()
        # 2.如果当前订单 end - start 存在且小于0，
        if pay_price_policy.end_datetime and pay_price_policy.end_datetime < datetime.datetime.now():
            request.chart_web.price_policy = free_price_policy
        else:
            # 3.封装免费的额度，
            request.chart_web.price_policy = pay_price_policy.price_policy

